/**
 * @param {number[][]} grid
 * @param {number} x
 * @return {number}
 */
 var minOperations = function(grid, x) {
  const arr = grid.flat(), n = arr.length
  arr.sort((a,b) => a-b)
  const mid = arr[n >> 1]
  let ans = 0
  for(const num of arr){
    let now = Math.abs(num - mid)
    if(now % x !== 0){
      return -1
    }
    ans += now/x
  }  
  return ans
};